<template>
  <div>
    <a-card class="contentFullHeight"  :bodyStyle="{padding : '10px 10px'}">
      <div class="">
        <a-card :bordered="true" class="searchBox" :bodyStyle="{padding : '10px 24px'}">
          <a-form layout="inline">

            <a-form-item label="用户名称">
              <a-input v-model="searchParams.name"></a-input>
            </a-form-item>

            <a-form-item >
              <a-button type="primary" icon="search" @click="handleSearch">查询</a-button>
            </a-form-item>

            <a-form-item v-if="isAuth('sys:user:save')">
              <a-button type="primary" icon="plus" @click="handleCreate">新增</a-button>
            </a-form-item>

            <a-form-item v-if="isAuth('sys:user:delete')">
              <a-button type="primary" icon="delete" :disabled="selectedRowKeys.length === 0" @click="handleCreate">批量删除</a-button>
            </a-form-item>

          </a-form>
        </a-card>
      </div>


      <a-table :columns="columns" :dataSource="data"
               :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
               bordered size="small" rowKey="id"
               :pagination="pagination" :loading="loading"
               @change="handleTableChange"
      >

        <template slot="name" slot-scope="text,record">
          <a href="javascript:;">{{text}}</a>
        </template>

        <template slot="sysUserRoles" slot-scope="text,record">
          <a-tag  v-for="item in text">{{item.roleName}}</a-tag>
        </template>

        <template slot="serviceIds" slot-scope="text,record">
         {{text.length}}个
        </template>

        <template slot="status" slot-scope="text,record">
          {{ text === 0 ? '禁用':'正常'}}
        </template>

        <span slot="action" slot-scope="text, record">
        <template>
           <a v-if="isAuth('sys:user:role')"  href="javascript:;"  @click="handleBindService(record)">绑定片区/服务点</a>
           <a-divider type="vertical"/>
          <a v-if="isAuth('sys:user:role')"  href="javascript:;"  @click="handleSetRole(record)">分配角色</a>
          <a-divider type="vertical"/>
          <a v-if="isAuth('sys:user:update')"  href="javascript:;"  @click="handleUpdate(record)">修改</a>
          <!--<a-divider type="vertical"/>-->
          <!--<a v-if="isAuth('sys:user:delete')"  href="javascript:;"  @click="handleDelete(record)">删除</a>-->
        </template>
      </span>

      </a-table>

      <a-modal  :maskClosable="false"
        :title="mdl.dialogTitleMap[mdl.dialogStatus]"
        :width="500"
        v-model="mdl.visible"
        @ok="mdl.dialogStatus === 'create' ? createData() : updateData()"
      >
        <a-form>

          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="账号"
          >
            <a-input placeholder="" v-model="mdl.formData.account"  />
          </a-form-item>

          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="密码"
          >
            <a-input placeholder="" v-model="mdl.formData.password"  />
          </a-form-item>

          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="用户姓名"
          >
            <a-input placeholder="" v-model="mdl.formData.userName"  />
          </a-form-item>

          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="部门"
          >
            <DeptTree v-model="mdl.formData.deptId"></DeptTree>
            <!--<a-input placeholder="" v-model="mdl.formData.deptId"  />-->
          </a-form-item>

          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="邮箱"
          >
            <a-input placeholder="" v-model="mdl.formData.email"  />
          </a-form-item>

          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="手机号"
          >
            <a-input placeholder="" v-model="mdl.formData.phone"  />
          </a-form-item>


          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="用户状态"
          >
            <a-radio-group  v-model="mdl.formData.status">
              <a-radio :value="0">启用</a-radio>
              <a-radio :value="1">禁用</a-radio>
            </a-radio-group>

          </a-form-item>

        </a-form>
      </a-modal>


      <a-modal  :maskClosable="false"
        v-if="mdl_role.visible"
        title="分配角色"
        :width="500"
        v-model="mdl_role.visible"
        @ok="setRole"
      >
        <a-form>
          <a-form-item
            :labelCol="mdl.labelCol"
            :wrapperCol="mdl.wrapperCol"
            label="系统角色"
          >
            <RoleSelect v-model="mdl_role.formData.roleIds" mode="multiple"></RoleSelect>
          </a-form-item>

        </a-form>
      </a-modal>

    </a-card>


  </div>
</template>

<script>
  import RoleSelect from "@/hzjComponents/select/RoleSelect"
  import DeptTree from "@/hzjComponents/treeSelect/DeptTree"
  import {
    getSysUserList
  } from '@/api/sysUser'
  const align = 'center'
 const  columns = [
   {
     title: '账号',
     dataIndex: 'userName',
     align
   },
//   {
//     title: '全称',
//     dataIndex: 'fullName',
//     align
//   },
   {
     title: '部门',
     dataIndex: 'deptName'
   },
   // {
   //   title: '岗位',
   //   dataIndex: 'job'
   // },
   {
     title: '邮箱',
     dataIndex: 'email',
     align
   },
   {
     title: '手机号',
     dataIndex: 'phone',
     align
   },
   {
     title: '系统角色',
     dataIndex: 'sysUserRoles',
     align,
     scopedSlots: { customRender: 'sysUserRoles' }

   },
   {
     title: '用户状态',
     dataIndex: 'status',
     align,
     scopedSlots: { customRender: 'status' }

   },
   {
     title: '操作',
     dataIndex: 'action',
     width: '350px',
     align,
     scopedSlots: { customRender: 'action' }
   }
   ]


  export default {

    components: {
      RoleSelect , DeptTree
    },
    data() {
      return {

        /*   -------搜索框--------*/
        searchParams :{
          name:''
        },


        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },

        /*   -------新增修改弹窗--------*/
        mdl: {
          dialogStatus: '',
          dialogTitleMap: {
            update: '编辑',
            create: '添加'
          },
          visible :false ,
          title:'',
          formData:{
            account:'',//账号
            password:'',//密码
            userName:'',//用户名
            deptId:null ,//部门
            email:'',//邮箱
            phone:'',//电话
            status:0 //0启用 1禁用
          },
        },

        /*   -------弹窗-设置角色--------*/
        mdl_role: {
          visible :false ,
          formData:{userId :'',roleIds:[]},

        },

        /*   -------弹窗-绑定 片区/供水站/服务点--------*/
        mdl_area: {
          visible :false ,
          formData:{userId :'',serviceIds:[]},

        },

        /*   -------表格--------*/

        loading: false,
        columns,
        data: [],
        selectedRowKeys: [], // Check here to configure the default column
        pagination: this.$defaultSettings.pagination ,
      }
    },
    inject: ['upShow'],filters: {},
    created() {

    },
    mounted() {
      this.getTableData()
    },
    methods: {

      onSelectChange(selectedRowKeys) {
        console.log('selectedRowKeys changed: ', selectedRowKeys);
        this.selectedRowKeys = selectedRowKeys;
      },


      handleTableChange(pagination, filters, sorter) {
        this.pagination = pagination
        let sortOrder = ''
        let sortField = sorter.field ? sorter.field : ''
        if (sorter.order) {
          sortOrder = sortOrder === 'ascend' ? 'asc' : 'desc'
        }
        this.getTableData(sortField, sortOrder)
      },

      getTableData(sortField, sortOrder) {


        this.loading = true

        const parameter = {
          _search: true,//是否分页查询
          pageSize: this.pagination.pageSize || 10,
          pageNumber: this.pagination.current || 1,
          sortField: sortField || '',
          sortOrder: sortOrder || '',
          // data:this.searchParams
          data: this.searchParams
        }
        getSysUserList(parameter).then(res=>{
          if(res.code===200){
            this.data=res.data.records;
            this.pagination.total=res.data.total;
            this.loading = false
          }
          this.loading = false
        }).catch(()=>{
          this.loading = false
          }
        )
      },
      handleSearch(){
        this.pagination.current = 1
        this.getTableData()
      },

      setDefaults(){
        this.mdl.formData = {
          account:'',//账号
          password:'',//密码
          userName:'',//用户名
          deptId:null ,//部门
          email:'',//邮箱
          phone:'',//电话
          status:0 //0启用 1禁用
        }
      },
      //添加行
      handleCreate() {
        this.setDefaults()
        this.mdl.dialogStatus = 'create'
        this.mdl.visible = true
        // this.$nextTick(() => {
        //   this.$refs['dataForm'].clearValidate()
        // })
      },
      createData(){
        //新增数据
        const  params = {...this.mdl.formData}
        this.$axios
          .post(this.$URLMAP.url.user.add, params)
          .then((response) => {
            if (response.code === 200) {
              this.upShow(1, '用户新增成功')
              this.mdl.visible = false
              this.handleSearch()
            } else {
              this.upShow(2, res.msg || '用户新增失败')
            }
          }).catch(err => {
          this.upShow(2, '新增用户接口调用失败')
        })
      },


      //编辑当前行
      handleUpdate(row) {
        console.log("这一行",row)
        this.mdl.formData = Object.assign({}, row) // copy obj
        this.mdl.dialogStatus = 'update'
        this.mdl.visible = true
        // this.$nextTick(() => {
        //   this.$refs['dataForm'].clearValidate()
        // })
      },

      updateData(){
        const  params = {
         id : this.mdl.formData.id ,
          account : this.mdl.formData.account ,
          password : this.mdl.formData.password ,
          userName : this.mdl.formData.userName ,
          deptId : this.mdl.formData.deptId ,
          email : this.mdl.formData.email ,
          phone : this.mdl.formData.phone ,
          status : this.mdl.formData.status ,
        }
        this.$axios
          .put(`${this.$URLMAP.url.user.update}/${params.id}`, params)
          .then((response) => {
            if (response.code === 200) {
              this.upShow(1, '用户修改成功')
              this.mdl.visible = false
              this.handleSearch()
            } else {
              this.upShow(2, res.msg || '用户修改失败')
            }
          }).catch(err => {
          this.upShow(2, '修改用户接口调用失败')
        })
      },

      handleDelete(row){
        this.upShow(2,"删除数据")
      },

      handleHandbookCustomer(row){
        this.upShow(2,"查看用户用户")
      },

      //分配角色
      handleSetRole(row) {
        this.mdl_role.formData.userId = row.id
        this.mdl_role.formData.roleIds = row.roleIds
        this.mdl_role.visible = true
        // this.$nextTick(() => {
        //   this.$refs['dataForm'].clearValidate()
        // })
      },
      setRole(){
        //设置角色
        const params = {
          userId : this.mdl_role.formData.userId,
          ids : this.mdl_role.formData.roleIds
        }
        this.$axios
          .post(this.$URLMAP.url.user.roles.set, params)
          .then((response) => {
            if (response.code === 200) {
              this.upShow(1, '用户角色设置成功')
              this.mdl_role.visible = false
              this.handleSearch()
            } else {
              this.upShow(2, res.msg || '用户角色设置失败')
            }
          }).catch(err => {
          this.upShow(2, '用户角色设置接口调用失败')
        })
      },


    }
  }
</script>

<style scoped>

</style>